import React, { useEffect, useRef, useState } from 'react'
import styles from './index.module.less'

type captchaType = {
    captchaVal?: string
    getTrueCaptcha: (val: string) => void
}

export default function Captcha({ captchaVal, getTrueCaptcha }: captchaType) {

    // 验证码
    const [captchaArr] = useState([])


    // 点击验证码输入框的事件
    const handleCanvas = () => {
        console.log('点击了验证码  ==》 刷新')
        draw(captchaArr)
    }

    // 显示验证码
    const draw = (show_num?: any) => {

        const canvas = document.getElementById("canvas") as any; //获取到canvas
        const context = canvas.getContext("2d");
        canvas.width = 130;
        canvas.height = 33;


        const sCode = "a,b,c,d,e,f,g,h,i,j,k,l,m,n,o,p,q,r,s,t,u,v,w,x,y,z,A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z,1,2,3,4,5,6,7,8,9,0";
        const aCode = sCode.split(",");
        const aLength = aCode.length;


        for (let i = 0; i <= 3; i++) {
            const j = Math.floor(Math.random() * aLength) + 1; //获取到随机的索引值
            const deg = (Math.random() * 30 * Math.PI) / 180; //产生0~30之间的随机弧度
            const txt = aCode[j]; //得到随机的一个内容
            show_num[i] = txt.toLowerCase();// 依次把取得的内容放到数组里面
            const x = 10 + i * 20; //文字在canvas上的x坐标
            const y = 20 + Math.random() * 8; //文字在canvas上的y坐标
            context.font = "bold 28px 微软雅黑";

            context.translate(x, y);
            context.rotate(deg);

            context.fillStyle = randomColor();
            context.fillText(txt, 0, 0);

            context.rotate(-deg);
            context.translate(-x, -y);
        }

        // 验证码上显示6条线条
        for (let i = 0; i <= 5; i++) {
            context.strokeStyle = randomColor();
            context.beginPath();
            context.moveTo(
                Math.random() * 130,
                Math.random() * 33
            );
            context.lineTo(
                Math.random() * 130,
                Math.random() * 33
            );
            context.stroke();
        }
        
        // 验证码上显示31个小点
        for (let i = 0; i <= 30; i++) {
            context.strokeStyle = randomColor();
            context.beginPath();
            const x = Math.random() * 130;
            const y = Math.random() * 33;
            context.moveTo(x, y);
            context.lineTo(x + 1, y + 1);
            context.stroke();
        }

        const num = show_num.join("");
        getTrueCaptcha(num)
    }

    //获取随机色
    const randomColor = () => {
        const r = Math.floor(Math.random() * 256);
        const g = Math.floor(Math.random() * 256);
        const b = Math.floor(Math.random() * 256);
        return "rgb(" + r + "," + g + "," + b + ")";
    }

    useEffect(() => {
        draw(captchaArr)
    }, [])

    return (
        <canvas className={styles.canvas} id="canvas" onClick={handleCanvas}></canvas>
    )
}
